-- INCLUDES
VFS.Include("LuaRules/Gadgets/Includes/utilities.lua")
VFS.Include("LuaRules/Gadgets/Includes/messagetypes.lua")

-- CONSTANTS
local GAIA_TEAM_ID = Spring.GetGaiaTeamID()
local LOCALPLAYER = Spring.GetMyPlayerID()
local SCOREBOARDWIDTH = 100

-- SYNCED CONTROLS
local Echo = Spring.Echo

-- CHILI CONTROLS
local Chili      
local Window     
local LableMaker 

-- MEMBERS
local scores = {}
local windows = {}
local x
local y

-- SCRIPT FUNCTIONS
function doPointUpdate(team, points)
	scores[team+1]:SetCaption(points)
end

function addScoreLabel(team)
	if DEBUG then Echo("adding scorecounter for team " .. team) end
	r,g,b,a = Spring.GetTeamColor(team)
	scores[team+1] = LableMaker:New{
		x = (SCOREBOARDWIDTH * team)+50,
		y = '10%',
		caption = "0",
		fontsize = 13,
		autosize = false,
		textColor = {r,g,b,a},
		anchors = {left=true,bottom=true,right=true},
	}	
end


-- WIDGET CODE
function widget:GetInfo()
	return {
		name		= "scoreboard",
		desc		= "scoreboard to keep ticker score",
		author		= "Sunspot",
		date		= "2011-06-13",
		license     = "GNU GPL v2",
		layer		= 1,
		enabled   	= true  --  loaded by default?
	}
end

function widget:Shutdown()
	for i=1,#windows do
		(windows[i]):Dispose()
	end
end

function widget:Initialize()
	
	if (not WG.Chili) then
		widgetHandler:RemoveWidget()
		return
	end
	Chili      = WG.Chili
	Window     = Chili.Window
	LableMaker = Chili.Label

	local screen0 = Chili.Screen0

	x = 0
	y = 40
	local teamList = Spring.GetAllyTeamList()
	if DEBUG then Echo("there are " .. table.getn(teamList) .. " ally teams") end
	-- -1 because of gaia being counted as an extra ally team
	local totalTeams = table.getn(teamList)-1
	for i=1, #teamList do
		if(teamList[i] ~= GAIA_TEAM_ID)then		
			addScoreLabel(teamList[i])	
		end
	end
		
	window0 = Window:New{
		x = '50%',
		y = '15%',	
		dockable = true,
		parent = screen0,
		caption = "scores",
		draggable = true,
		resizable = false,
		dragUseGrip = true,
		clientWidth = SCOREBOARDWIDTH * totalTeams,
		clientHeight = 20,
		backgroundColor = {0.8,0.8,0.8,0.9},
		skinName  = "DarkGlass",	
		
		children = scores,
	}
	windows[#windows+1] = window0	
end

function widget:RecvLuaMsg(msg, playerID)
	if (playerID ~= LOCALPLAYER) then return end
	
	local tokens = split(msg,"-");
	if(tokens[1] == POINTUPDATE)then
		if DEBUG then Echo("recieved point update msg for team " .. tokens[2] .. " with score " .. tokens[3]) end
		doPointUpdate(tokens[2],tokens[3])
	end

end